var pageindex  = 1;
var pagesize  = 12;
var PageTotal = 0;
var PageMax   = 1;
var container = $('.waterfull ul');
var loading = $('#imloading');


$(function() {
	$('.variety-title li').click(function() {
		$(this).addClass('active').siblings().removeClass('active');
		//$('.tab-top li').eq($(this).index()).addClass('active').siblings().removeClass('active');  tab按钮第二种写法
		// var index = $(this).index();
		// $(".variety-content").eq(index).show().siblings().hide();
	})


	/*瀑布流开始*/
	// 初始化loading状态
	loading.data("on", true);
	/*判断瀑布流最大布局宽度，最大为1280*/
	function tores() {
		var tmpWid = $(window).width();
		if (tmpWid > 1000) {
			tmpWid = 1000;
		} else {
			var column = Math.floor(tmpWid / 250);
			tmpWid = column * 250;
		}
		$('.waterfull').width(tmpWid);
	}
	tores();
	$(window).resize(function() {
		tores();
	});
	container.imagesLoaded(function() {
		container.masonry({
			columnWidth: 250,
			itemSelector: '.item',
			isFitWidth: true, //是否根据浏览器窗口大小自动适应默认false
			isAnimated: true, //是否采用jquery动画进行重拍版
			isRTL: false, //设置布局的排列方式，即：定位砖块时，是从左向右排列还是从右向左排列。默认值为false，即从左向右
			isResizable: true, //是否自动布局默认true
			animationOptions: {
				duration: 800,
				easing: 'easeInOutBack', //如果你引用了jQeasing这里就可以添加对应的动态动画效果，如果没引用删除这行，默认是匀速变化
				queue: false //是否队列，从一点填充瀑布流
			}
		});
	});

	/*本应该通过ajax从后台请求过来类似sqljson的数据然后，便利，进行填充，这里我们用sqlJson来模拟一下数据*/
	$(window).scroll(function() {
		if (!loading.data("on")) return;
		// 计算所有瀑布流块中距离顶部最大，进而在滚动条滚动时，来进行ajax请求，方法很多这里只列举最简单一种，最易理解一种
		var itemNum = $('#waterfull').find('.item').length;
		var itemArr = [];
		itemArr[0] = $('#waterfull').find('.item').eq(itemNum - 1).offset().top + $('#waterfull').find('.item').eq(itemNum - 1)[0].offsetHeight;
		itemArr[1] = $('#waterfull').find('.item').eq(itemNum - 2).offset().top + $('#waterfull').find('.item').eq(itemNum - 1)[0].offsetHeight;
		itemArr[2] = $('#waterfull').find('.item').eq(itemNum - 3).offset().top + $('#waterfull').find('.item').eq(itemNum - 1)[0].offsetHeight;
		var maxTop = Math.max.apply(null, itemArr);
		if (maxTop < $(window).height() + $(document).scrollTop()) {
			//加载更多数据
			loading.data("on", false).fadeIn(800);
			pageindex = pageindex + 1;
			if (pageindex<= PageMax)
			{
				getPictureList();
			}else{
				loading.html("已经到底了！");
			}
			
		}
	});
	getPictureList();
	setPicNav();

	$(".orderby").on("click",function(){
		$(".masonry").html("");
		container.masonry();
		$(this).siblings().removeClass("act");
		$(this).addClass("act");
		getPictureList();

	});

});

function setPicNav(){
	
	if($(".variety-title").length==1){
		setTimeout(function(){
			var channel = GetUrlParam("t")
			var columnid= GetUrlParam("columnid")
			if(channelList){
				var piclist =channelList.filter(function(c){
					return c.id==channel
				});
				$(".variety-title div ul").append("<li class='" + ("0"==columnid?"active":"") + "'><a href='picture.shtml?t="+ channel +"&columnid=0'>推荐</a></li>")
				if(piclist.length==1){
					piclist = piclist[0];
					for(var i = 0; i<piclist.children.length;i++){
						$(".variety-title div ul").append("<li class='" + (piclist.children[i].id==columnid?"active":"") +"'><a href='pictureVariety.shtml?t="+ channel +"&columnid="+ piclist.children[i].id +"'>"+ piclist.children[i].columnName +"</a></li>")
					}
				}
			}else{
				setPicNav();
			}
		},0);
	}
}

function loadImage(url) {
	var img = new Image();
	//创建一个Image对象，实现图片的预下载
	img.src = url;
	if (img.complete) {
		return img.src;
	}
	img.onload = function() {
		return img.src;
	};
};

function getPictureList(){
	var columnid= GetUrlParam("columnid")||0
	
	var orderby = $(".orderby.act").data("orderby")
	
	var channel = GetUrlParam("t");
	$.ajax({
		type: "get",
		async: false,
		url: "http://api.elementos.com.cn/PictureList.aspx?columnid="+columnid+"&pageindex="+pageindex+"&pagesize="+pagesize+"&orderby="+orderby,
		dataType: "jsonp",
		data: "",
		jsonp: "callback",
		success:function (json) {
			let sqlJson = json.data.list;
			PageTotal = json.data.total;
			PageMax = Math.ceil(PageTotal/pagesize);

			var html = "";
			for (var i in sqlJson) {
				html += "<li class='item'><a href='pictureDetails.shtml?t="+ channel +"&columnid="+columnid+"&id="+sqlJson[i].id+"' class='a-img'><img src='" + sqlJson[i].cover + "'><div class='design' ><span>"+ sqlJson[i].columnname +"</span><span>"+ sqlJson[i].total+"<span></div></a>";
				// html += "<h2 class='li-title'>" + sqlJson[i].title + "</h2>";
				// html += "<p class='description'>" + sqlJson[i].intro + "</p><div class='qianm clearfloat'>";
				html += "<div class='column-items-describle'>";
				html += "<div>" + sqlJson[i].publishdate + "</div>";
				html += "<div>" + sqlJson[i].title + "</div>";
				html += "<div>" + sqlJson[i].username + "</div>";
				html += "</div>"
			}
			/*模拟ajax请求数据时延时800毫秒*/
			var time = setTimeout(function() {
				$(html).find('img').each(function(index) {
					loadImage($(this).attr('src'));
				})
				var $newElems = $(html).css({
					opacity: 0
				}).appendTo(container);
				$newElems.imagesLoaded(function() {
					$newElems.animate({
						opacity: 1
					}, 800);
					container.masonry('appended', $newElems, true);
					loading.data("on", true).fadeOut();
					clearTimeout(time);
				});
			}, 800)
		}
	});

};

function GetUrlParam(paraName) {
    var url = document.location.toString();
    var arrObj = url.split("?");
    if (arrObj.length > 1) {
        var arrPara = arrObj[1].split("&");
        var arr;
        for (var i = 0; i < arrPara.length; i++) {
            arr = arrPara[i].split("=");
            if (arr != null && arr[0] == paraName) {
                subjectID = arr[1];
                return arr[1];
            }
        }
        return "";
    } else {
        return "";
    }
}
